package com.lz.comm.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.InputFilter;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatEditText;

import com.lz.comm.R;

/**
 * Created by you on 2019/9/27.
 */

public class SpecialEditText extends AppCompatEditText {

    private int specialMaxLength;

    public SpecialEditText(Context context) {
        super(context);
        init(context, null);
    }

    public SpecialEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public SpecialEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        if (attrs != null) {
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SpecialEditText);
            specialMaxLength = a.getInt(R.styleable.SpecialEditText_specialMaxLength, specialMaxLength);
            a.recycle();
        }
        if (specialMaxLength > 0) {
            InputFilter[] filters = this.getFilters();
            if (filters == null || filters.length == 0) {
                //没有过滤项直接添加
                this.setFilters(new InputFilter[]{new SpecialLengthFilter(specialMaxLength)});
                return;
            }
            //是否有自带的限制字数
            boolean hasLengthFilter = false;
            for (int i = 0; i < filters.length; i++) {
                if (filters[i] instanceof InputFilter.LengthFilter) {
                    filters[i] = new SpecialLengthFilter(specialMaxLength);
                    hasLengthFilter = true;
                    break;
                }
            }
            //没有自带的限制字数，再新添加
            if (!hasLengthFilter) {
                InputFilter[] newFilters = new InputFilter[filters.length + 1];
                System.arraycopy(filters, 0, newFilters, 0, filters.length);
                newFilters[filters.length] = new SpecialLengthFilter(specialMaxLength);
                this.setFilters(newFilters);
            } else {
                this.setFilters(filters);
            }
        }
    }

}
